package com.es.servlet; /**
 * 描述:
 * es-jsp-
 *
 * @author Derek
 * 创建时间：2022-04-28 11:10
 */

import com.es.util.DBUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

@WebServlet(name = "FileUploadServlet", value = "/upload")
public class FileUploadServlet extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //先判断是否是 文件上传的请求

        boolean isMultiRequest = ServletFileUpload.isMultipartContent(request);

        if(isMultiRequest){
            //进行文件上传的设置
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            //临时目录
            File tempDir = new File("e:/temp");
            diskFileItemFactory.setRepository(tempDir);
            //设置一个临界值，超过临界值会先临时存放到tempDir
            diskFileItemFactory.setSizeThreshold(1024*1024);
            //创建用于解析request的对象
            ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
            upload.setHeaderEncoding("utf-8");
            Connection connection = DBUtils.getConnection();
            try {
                List<FileItem> itemList = upload.parseRequest(request);
                FileItem fileItem = itemList.get(0);
                InputStream inputStream = fileItem.getInputStream();
                //
                String webappRoot = request.getServletContext().getRealPath("/");
                File rootDir = new File(webappRoot);
                //上传目录
                File destDir = new File(rootDir, "uploads/");
                if(!destDir.exists()){
                    destDir.mkdir();
                }
                String filePath = destDir.getAbsolutePath()+"/"+ UUID.randomUUID().toString()+fileItem.getName().substring(fileItem.getName().lastIndexOf("."));
                FileOutputStream fileOutputStream = new FileOutputStream(filePath);
                File descFile = new File(filePath);
                //  保存到目标文件
                fileItem.write(descFile);
                //把文件信息存储到数据中
                String sql = "insert into sys_upload_files(old_name,file_length,file_type,file_path) values (?,?,?,?)";
                connection.setAutoCommit(false);
                PreparedStatement ps = connection.prepareStatement(sql);
                ps.setString(1, fileItem.getName());
                ps.setLong(2,fileItem.getSize());
                ps.setString(3, fileItem.getContentType());
                ps.setString(4,filePath);
                ps.executeUpdate();
                connection.commit();
                ps.close();
                connection.close();
            } catch (FileUploadException e) {
                try {
                    connection.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
                e.printStackTrace();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
